import pandas as pd
import argparse
from decimal import Decimal, getcontext

getcontext().prec = 10

def get_row_from_file(file):
    with open(file) as f:
        next(f)
        for _ in range(2):
            next(f)
            col1 = [v for v in f.readline().split()]
            col2 = [v for v in f.readline().split()]
            col3 = [v for v in f.readline().split()]
            col = [x + y + z for x, y, z in zip(col1, col2, col3)]
            data = []
            while True:
                l = f.readline().strip()
                if not l:
                    break
                data.append([Decimal(num) for num in l.split()])
            yield pd.DataFrame(data, columns=col)

argp = argparse.ArgumentParser(
    description="Verify the output of OpenCAEPoro",
)
argp.add_argument('-r', '--ref', type=str, help='Reference Output', required=True)
argp.add_argument('-o', '--out', type=str, help='Your Output', required=True)
args = argp.parse_args()

ref = args.ref
out = args.out

ref_r1, ref_r2 = get_row_from_file(ref)
out_r1, out_r2 = get_row_from_file(out)

items = {
    "FPRPSIA-": "r1", "FOPRSTB/DAY-" : "r1", "FGPRMSCF/DAY-" : "r1", "FWPRSTB/DAY-" : "r1", 
    "WBHPPSIAINJE1" : "r2", "WBHPPSIAPROD1" : "r2"
    }
time_points = [Decimal(x) for x in [50.0, 180.0, 360.0, 720.0, 1080.0, 1440.0, 1800.0, 2160.0, 2520.0, 2880.0, 3240.0, 3600.0]]

find_valid = True
for item, key in items.items():
    sum = refd = outd = Decimal(0.0)
    for stamp in time_points:
        if key == "r1":
            refd = ref_r1.loc[ref_r1['TIMEDAY-'] == stamp, item].values[0]
            outd = out_r1.loc[out_r1['TIMEDAY-'] == stamp, item].values[0]
        else:
            refd = ref_r2.loc[ref_r2['TIMEDAY-'] == stamp, item].values[0]
            outd = out_r2.loc[out_r2['TIMEDAY-'] == stamp, item].values[0]
        part = abs(outd - refd)**2 / refd
        sum += part
        print("item {} in stamp {} part is {}".format(item, stamp, part))
    valid_result = sum / Decimal(12.0)
    is_valid = True if valid_result < Decimal(0.01) else False
    find_valid = find_valid and is_valid
    print("item {} sum is {}".format(item, sum))
    print("item {} Find Validation Result is {}, {} less than 0.01".format(
        item,
        valid_result,
        "" if is_valid else "Not"
    ))

if find_valid:
    print("Verification PASS!")
else:
    print("Verification Not PASS!")